package com.bigtomato.tomatochat.controller;


import com.bigtomato.tomatochat.entity.User;
import com.bigtomato.tomatochat.server.UserService;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
public class UserController {
    @Autowired
    UserService userService;

    @RequestMapping("/user/{username}")
    public @ResponseBody
    boolean isExistUsername(@PathVariable String username) {
        return userService.isExistUsername(username);
    }

    @RequestMapping("/login")
    public String login() {
        return "login";
    }

    @RequestMapping("/register")
    public String register() {
        return "register";
    }

    @RequestMapping("/tomatochat")
    public String tomatochat(Model model,HttpSession httpSession) {
        User user=(User)httpSession.getAttribute("user");
        model.addAttribute("user",user);
        return "tomatochat";
    }
    @RequestMapping(value = "/user/login", produces = "text/plain;charset=UTF-8")
    public @ResponseBody String userLogin(User user, HttpServletRequest request) {
        HttpSession httpSession = request.getSession();
        if (userService.userLogin(user)) {
            httpSession.setAttribute("user", user);
        }
        return String.valueOf(userService.userLogin(user));
    }
    @RequestMapping(value = "/user/register", produces = {"application/json;charset=UTF-8"})
    public @ResponseBody Map register(User user) {
        Map message=userService.userRegister(user);
        return message;
    }
    @RequestMapping(value = "/user/getRandAccount", produces = {"application/json;charset=UTF-8"})
    public @ResponseBody Map getRandAccount() {
        Map message=userService.getRandAccount();
        return message;
    }
}
